
var TetrisCanvas = function(grap){
	//========================常量声明==============================
	//屏幕参数
	var ROW			=20 ;	
	var COLUMN		=10;
	var BLOCK_WIDTH	=27;
	var BLOCK_HEIGHT	=27;
	var SQUARE_IMAGE_NUMS	=2;
	var BEGIN_X	=3;
	var BEGIN_Y	=0;
	var NEXT_X	=394;
	var NEXT_Y	=20;
	var SCREEN_WIDTH	=132;
	var SCREEN_HEIGHT	=176;
	var SMOKE_NUMS	=5;
	var KEY_RESPONSE_TIME	=30;
	var LEFT	=0;
	var TOP	=-2*BLOCK_HEIGHT;

	var nextBias =	[[0,0], // 1
						 [0,0],  // 2
						 [1,1],  // 3
						 [1,0],  // 4
						 [0,1],  // 5
						 [1,0],  // 6
						 [0,1],  // 7
						 [1,0],  // 8
						 [0,1],  // 9
						 [1,0],  // 10
						 [0,0],  // 11
						 [0,1],  // 12
						 [1,0],  // 13
						 [0,1],  // 14
						 [1,0],  // 15
						 [1,1],  // 16
						 [1,1],  // 17
						 [0,1],  // 18
						 [1,0]]; // 19
							 							  
 	//========================变量声明==============================
	var sleepTime = 600;
	var sleepStep =30 ; 
	var beginTime;
	var keyBeginTime;
	var fps, epb;
	
	var CANVAS_WIDTH = 600;
	var CANVAS_HEIGHT = 600 ;

	var base ;
	var current;
	var next;
	var bottom;

	var cpx,cpy ;
	var bottomY;
	var gameLevel ;
	var score ;	
	var moveLineIndex ;
	var smokeNums;
	var line3Nums;
	var line4Nums;

	var gameOver;
	var leftPressed, rightPressed, downPressed;

	var background;
	var nextBackgroud;
	var line3Image,line4Image;
	var gameOverImage;
	var numbers;
	
	var squareImages;
	var bottomSquareImage;
	var smoke;
	
	var g = grap;

	//==============================================================

		//start();
	//======================== method ==============================
	//------------ abstract method ---
	var paint = function()
	{
		//paint background
		g.fillRect(0,0,CANVAS_WIDTH,CANVAS_HEIGHT);
//		g.drawImage(background, 0, 0);

		//paint base
		for( var i=0 ; i< ROW ; i++)
			for( var j =0; j< COLUMN ; j++)
		{
			if( base[i][j] != null)
			{
				base[i][j].draw( j*BLOCK_WIDTH +LEFT, i*BLOCK_HEIGHT +TOP, g);			
			}
		}

		//paint status bar
		drawStatusBar(g);
		
		
		// paint bottom square
		bottom.draw( cpx*BLOCK_WIDTH +LEFT, bottomY*BLOCK_HEIGHT +TOP, g);

		// paint current SquareGroup
		current.draw( cpx*BLOCK_WIDTH +LEFT, cpy*BLOCK_HEIGHT +TOP, g);

		//paint next SquareGroup
		next.draw( NEXT_X + nextBias[ next.getType() ][0]*BLOCK_WIDTH, NEXT_Y+ nextBias[ next.getType() ][1]*BLOCK_HEIGHT,  g);

		g.setColor( 0x0099ff33 );
		//g.drawRect( LEFT, TOP, COLUMN*BLOCK_WIDTH, ROW*BLOCK_HEIGHT );
		g.drawLine( LEFT, 0, LEFT+COLUMN*BLOCK_WIDTH, 0 );

		if( smokeNums > 0 )
		{
			if( moveLineIndex != 0)
			{
				smokeNums  --;
				drawMoveLine( g );
			}
		}
		else
		{
			moveLineIndex = 0;
		}

		// ==  
		if( line3Nums > 0 )
		{
			line3Nums  --;
			if( (line3Nums/2)%2 == 0) 
				drawLineImage( 3,g );
			else if( line3Nums <= 2 )
				line3Nums =0;
		}
		else if( line4Nums > 0 )
		{
			line4Nums  --;
			if( (line4Nums/2)%2 == 0) 
				drawLineImage( 4,g );
			else if( line4Nums <= 2 )
				line4Nums =0;
		}	
	
		
		if( gameOver )
		{
			for( var i=0 ; i< ROW ; i++)
			for( var j =0; j< COLUMN ; j++)
			{
				if( base[i][j] != null)
				{
					base[i][j].draw( j*BLOCK_WIDTH +LEFT, i*BLOCK_HEIGHT +TOP, g);			
				}
			}
			g.drawImage( gameOverImage, SCREEN_WIDTH/2, SCREEN_HEIGHT/2 );
			return ;
		}	
	}

	var start = function()
	{
		gameOver = false;
		pause = false;
		
		for( var i=0 ; i< ROW ; i++)
			for( var j =0; j< COLUMN ; j++)
		{
			 base[ i ][ j ] = null ;			
		}
		newGroup();

		run();
	}
	

	var newGroup = function()
	{		
		cpx  = BEGIN_X;
		cpy  = BEGIN_Y;
		
		current = next;
		if( checkGameOver())
			return;
		next    = getSquareGroup();
		bottom = new SquareGroup( bottomSquareImage, current.getType() );
		findBottomPosition();	

	}

	var checkGameOver = function()
	{
		var bias = current.getBias();
		for( var i =0; i< 4; i++)
		{
			if( cpx+bias[i][0] < 0 || base[ cpy +bias[i][1] ][ cpx+bias[i][0] ] != null)
			{
				gameOver = true;
				return true;
			}
		}
		return false;
	}
	
	var drawStatusBar = function()
	{
		var width = 50;
		var height =50;

		g.setColor( 0x00ff0000 );
		g.drawString("Next",NEXT_X, NEXT_Y -15);
		
		g.setColor( 0x00ffff00);
		g.drawRect( NEXT_X -1, NEXT_Y-1, 4*width+2, 4*height+2);
		g.drawRect( NEXT_X -2, NEXT_Y-2, 4*width+4, 4*height+4);
		
		for( var i=0; i <4; i++)
			for( var j=0; j <4; j++)
			{
				//g.drawImage( nextBackgroud, NEXT_X+j*width ,NEXT_Y+i*height);
			}
			
		g.setColor( 0x00ffee00 );
		g.drawString("Level",NEXT_X, NEXT_Y +40 );
		drawNumbers(gameLevel,NEXT_X+5, NEXT_Y +55, g);

		g.drawString("Score",NEXT_X, NEXT_Y +65 );
		drawNumbers(score,NEXT_X, NEXT_Y +80, g);
		
	

	}	


	var drawMoveLine = function( )
	{
		for( var i=0; i <COLUMN ; i++)//moveLineIndex
		{
			if( i% 2 == 0)
				g.drawImage( smoke, i*BLOCK_WIDTH +LEFT, moveLineIndex*BLOCK_HEIGHT +TOP);
		}
	}

	var drawLineImage = function(line )
	{
		if( line == 3)
			g.drawImage( line3Image, SCREEN_WIDTH/4 +20, SCREEN_HEIGHT*1/3+20);
		else if( line == 4 )
			g.drawImage( line4Image, SCREEN_WIDTH/4 +20, SCREEN_HEIGHT*1/3+20);
	}	
	
	var getSquareGroup = function()
	{
		var type = parseInt( Math.random()*( SquareGroup.TYPE_NUMS ) );
		var imageType = parseInt( Math.random()*( SQUARE_IMAGE_NUMS ) );

		return new SquareGroup( squareImages[ imageType ] , type );
	}

	var moveLeft = function()
	{
		var bias = current.getBias();
		for( var i =0; i< 4; i++)
		{
			if( cpx+bias[i][0]-1 < 0 || base[ cpy +bias[i][1] ][ cpx+bias[i][0]-1 ] != null)
			{
				//System.out.println("Can't MoveLeft.");
				return ;
			}
		}
		cpx --;
		findBottomPosition();
	}

	var moveRight = function()
	{
		var bias = current.getBias();
		for( var i =0; i< 4; i++)
		{
			if( cpx+bias[i][0]+1 > COLUMN-1 ||  base[ cpy +bias[i][1] ][ cpx+bias[i][0]+1 ] != null)
				return ;
		}
		cpx ++;
		findBottomPosition();
	}

	var rotate = function()
	{
		var rotateBias = current.getRotateBias();

		for( var i =0; i< 4; i++)
		{
			if( cpx+rotateBias[i][0]>=COLUMN || cpy+rotateBias[i][1]+1>=ROW || base[ cpy+rotateBias[i][1] ][  cpx+rotateBias[i][0] ] != null )
			{//System.out.println("IN rotate NOT");
				return ;
			}
		}
		current.rotate();//System.out.println("out rotate ");
		bottom.rotate();
		findBottomPosition();
	}
	
	$(document).keydown(function(e)    
		    {   
		        switch(e.which)    
		        {    
		            // user presses the "UP"    
		            case 38:    rotate();    
		                        break;      
		                            
		            // user presses the "DOWN" key    
		            case 40:   toBottom();    
		                        break;    
		                            
		            // user presses the "LEFT" key    
		            case 37:   moveLeft();    
		                        break;    
		                            
		            // user presses the "RIGHT" key    
		            case 39:   moveRight();    
		                        break;    
		            case 32:   start();    
		                        break;    
		        }    
		        return false;
		    });  
	var moveDown = function()
	{
		//System.out.println("IN moveDown");
		var bias = current.getBias();
		//var x=0,y=0;

		for( var i =0; i< 4; i++)//base[x][y];//x:cpx+bias[i][0],Y:cpy+bias[i][1]+1
		{
			if( cpx+bias[i][0]>=COLUMN || cpy+bias[i][1]+1>=ROW || base[ cpy+bias[i][1]+1 ][  cpx+bias[i][0] ] != null )
			{
				hitBottom();//System.out.println("OUT moveDown");
				return ;
			}
		}
		cpy ++;//System.out.println("OUT moveDown");

		//if( moveLineIndex != 0)
		//	moveLineIndex = 0;
	}

	var hitBottom = function()
	{
		var bias = current.getBias();
		var lineNums =0;
		//var x=0,y=0;
		for( var i =0; i< 4; i++)
		{
			base[ cpy+bias[i][1] ][ cpx+bias[i][0]] = current.square;			
		}

		for( var i=0; i < ROW ; i++)
		{
			var j =0;
			for( ; j <COLUMN; j++)
			{
				if( base[i][j] == null)
					break;
			}
			if( j == COLUMN )
			{
				score +=100;
				lineNums ++;
				if( moveLineIndex < i )
					moveLineIndex = i;
				for( var k=i; k >0; k--)
				{
					for( j=0; j <COLUMN; j++)
					{
						base[k][j]= base[k-1][j];
					}
				}
				//System.out.println("REMOVE LINE2");
				for( j=0; j <COLUMN; j++)
					{
						base[0][j]= null;
					}
				//System.out.println("REMOVE LINE3");
			}
		}

		if( moveLineIndex != 0 )
		{
			smokeNums = SMOKE_NUMS;
		}

		if( lineNums == 1)
		{
			line3Nums = SMOKE_NUMS*5;
			score +=300;         //  bouns
		}
		if( lineNums == 4)
		{
			line4Nums = SMOKE_NUMS*5;
			score +=600;	    //  bouns
		}

		if( gameLevel < score / 10000 +1 )
		{
			gameLevel = score / 10000 +1 ;
			setSleepTime( -100 ); 
		}

	//System.out.println("REMOVE LINE4");

		//cpx = BEGIN_X;
		//cpy = BEGIN_Y;
		//current = getSquareGroup();
		//findBottomPosition();
		//System.out.println("OUT HieBOttom");
		newGroup();

	}

	var toBottom = function()
	{
		cpy = bottomY;
		hitBottom();
	}

	var findBottomPosition = function()
	{
		var bias = current.getBias();
		var done = false;
		var y = cpy;

		while( !done )
		{
			for( var i =0; i< 4; i++)//base[x][y];//x:cpx+bias[i][0],Y:cpy+bias[i][1]+1
			{
				if( cpx+bias[i][0]>=COLUMN || y+bias[i][1]+1>=ROW || base[ y+bias[i][1]+1 ][  cpx+bias[i][0] ] != null )
				{
					done = true;
					break;
				}
			}
			if( !done)
				y ++;
		}
		bottomY = y; 

	}	

	var setSleepTime = function( delta )
	{
		if( sleepTime+delta >=200 && sleepTime+delta <=600)
		{
			sleepTime += delta;
		}
	}




	var drawNumbers = function( num ,x,y)
	{
		g.drawString(num,x, y );
		return;
		var numStr = ""+num;
		
		var len = numStr.length;
		for( var i=0; i< len; i++)
		{//System.out.println("numByte="+numByte[i]);
			g.drawImage( numbers[numStr.charAt(i)-48  ],x,y);
			x += 8;
		}
	}	


	var input = function()
	{}
	
	
	var keyPressed = function(keyCode) 
	{}

	var i =0;
	var downNums = 10;
	var run = function()
	{
		//var beginTime = 0;
		var left = 0;
		var right =0;
		var down =0;

		var beginTime =0;
		var endTime =0;

		setInterval( function()
		{
			input();
			paint();
			i++;
			if( i >= downNums )
			{
				i = 0;	
				moveDown();
			}

		},100);

	};
	
	
	// 
		stop= false;
		pause = false;
		gameOver = false;
		gameLevel =1;

		numbers = new Array();
		squareImages = new Array();
			background = Image.createImage("bg_1.png");
			nextBackgroud =  Image.createImage( "s3_2.png");
			line3Image  = Image.createImage("line3.png");
			line4Image  = Image.createImage("line4.png");
			gameOverImage = Image.createImage("gameover.png");

			var image = Image.createImage("numbers.png");		
			var x = 0 ;
			
			for( var i=0 ; i< 10 ; i++)
			{
				numbers[i] = image;
				x += 6;
			}

			x = 0;
			for( var i=0 ; i< SQUARE_IMAGE_NUMS ; i++)
			{
				image = Image.createImage("s3.png");
				squareImages[ i] = image;
				x += BLOCK_WIDTH;
			}	
			
			bottomSquareImage =  Image.createImage("bottoms3.png");
			smoke = Image.createImage( "bom.png" );



		//pause = false;
		base = new Array();
		for(var i=0;i<ROW;i++){
			base[i] = [];
			for(var j=0;j<COLUMN;j++){
				base[i][j] = new Square();
			}
			
		}

		next = getSquareGroup();
		
		start();

};


$(function(){
	Image.createImage = function(src){
		var img = new Image();
		img.src = '/images/t/'+src;
		return img ;
	}
	var canvas = document.getElementById("canvas");
      if (canvas.getContext) {
	        var ctx = canvas.getContext("2d");
	
	        
	        ctx.fillStyle = "#99ff33";
	        
	        ctx.setColor = function(color){
	        	ctx.fillStyle = "#"+ (""+color).replace(/^.*(\d{6})$/,'$1');
	        }
	        ctx.drawString = function(str,x,y){ctx.fillText(str,x,y);}
	        ctx.drawRect = function(x,y,w,h){ctx.fillRect(x,y,w,h);}
	        ctx.drawLine = function(x,y,tx,ty){
	        	ctx.beginPath();
			    ctx.moveTo(x,y);
			    ctx.lineTo(tx,ty);
			    ctx.stroke();
			}
	        
	        //ctx.fillRect (10, 10, 55, 50);
	
	        var c = new TetrisCanvas(ctx);
	        
//	       var  nextBackgroud =  Image.createImage( "tm_logo2.png");
//	       nextBackgroud.onload = function(){
//	    	ctx.drawImage(nextBackgroud,0,0);
//	       }
//       
//	      var img = new Image();
//	      img.src = '/images/t/backdrop.png';
//	      img.onload = function(){
//	        ctx.drawImage(img,0,0);
//	        ctx.beginPath();
//	        ctx.moveTo(30,96);
//	        ctx.lineTo(70,66);
//	        ctx.lineTo(103,76);
//	        ctx.lineTo(170,15);
//	        ctx.stroke();
//	      }
        
      }
});